package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.Articulo;

public class ArticuloDAOImpl extends JdbcDaoSupport implements IArticuloDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;
    
    public FindListByCriteriaQuery findListByCriteriaQuery;

    private FindAllQuery findAllQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM GES_ARTICULO_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(Articulo articulo) {
		deleteOperation.execute( articulo  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public Articulo findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(Articulo articulo) {
		insertOperation.execute( articulo );
	}

	public void update(Articulo articulo) {
		updateOperation.execute( articulo );
	}

	public Articulo findByCriteria(Articulo  articulo) {
		return findByCriteriaQuery.runQuery(articulo);
	}

	public List load(Articulo  articulo) {
		return findAllQuery.runQuery(articulo);
	}

	public Articulo findByActiveState(Articulo  articulo) {
		return findByActiveStateQuery.runQuery(articulo);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findListByCriteriaQuery = new FindListByCriteriaQuery( getDataSource() );
    	//Disabled
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO GES_ARTICULO_T ("
				  + " ID, "
				  + " CODIGO, "
				  + " DESCRIPCION, "
				  + " DESCRIPCION_ADICIONAL, "
				  + " ID_UNIDAD_MEDIDA, "
				  + " PESO, "
				  + " VOLUMEN, "
				  + " ID_SUB_GRUPO_ARTICULO, "
				  + " ID_AREA_RESPONSABLE, "
				  + " VALOR_UNITARIO, "
				  + " ID_UNIDAD_MEDIDA_COMPRA, "
				  + " DESCRIPCION_COMPRA, "
				  + " ID_TIPO_MATERIAL, "
				  + " PROPIO, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "
				  + ") VALUES ("
			  	  + " GES_ARTICULO_SEC.nextVal, "
			  	  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(Articulo articulo) {
			InsertOperation.this.update( new Object[]{
				articulo.getCodigo(),
				articulo.getDescripcion(),
				articulo.getDescripcionAdicional(),
				articulo.getIdUnidadMedida(),
				articulo.getPeso(),
				articulo.getVolumen(),
				articulo.getIdSubGrupoArticulo(),
				articulo.getIdAreaResponsable(),
				articulo.getValorUnitario(),
				articulo.getIdUnidadMedidaCompra(),
				articulo.getDescripcionCompra(),
				articulo.getIdTipoMaterial(),
				articulo.getPropio(),
				articulo.getEstado(),
				articulo.getUsuarioCrea()
			});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE GES_ARTICULO_T SET "
					  + " CODIGO = ? ,"
					  + " DESCRIPCION = ? ,"
					  + " DESCRIPCION_ADICIONAL = ? ,"
					  + " ID_UNIDAD_MEDIDA = ? ,"
					  + " PESO = ? ,"
					  + " VOLUMEN = ? ,"
					  + " ID_SUB_GRUPO_ARTICULO = ? ,"
					  + " ID_AREA_RESPONSABLE = ? ,"
					  + " VALOR_UNITARIO = ? ,"
					  + " ID_UNIDAD_MEDIDA_COMPRA = ? ,"
					  + " DESCRIPCION_COMPRA = ? ,"
					  + " ID_TIPO_MATERIAL = ? ,"
					  + " PROPIO = ? ,"
					  + " ESTADO = ? ,"
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE "
				  	  + WHERE
			  	  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(Articulo articulo) {
			UpdateOperation.this.update( new Object[]{
				articulo.getCodigo(),
				articulo.getDescripcion(),
				articulo.getDescripcionAdicional(),
				articulo.getIdUnidadMedida(),
				articulo.getPeso(),
				articulo.getVolumen(),
				articulo.getIdSubGrupoArticulo(),
				articulo.getIdAreaResponsable(),
				articulo.getValorUnitario(),
				articulo.getIdUnidadMedidaCompra(),
				articulo.getDescripcionCompra(),
				articulo.getIdTipoMaterial(),
				articulo.getPropio(),
				articulo.getEstado(),
				articulo.getUsuarioModifica(),
				articulo.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_ARTICULO_T "
										+ WHERE
			  	  	  					+ " CODIGO = ? ";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
		}
		public void execute(Articulo articulo) {
			this.update( new Object[]{
				articulo.getCodigo(),
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_ARTICULO_T "
										+ WHERE + " 1=1 "
			  	  	  					+ " ID = ? ";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
					new Long(id)
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Articulo articulo = new Articulo();
				articulo.setId(new Long(rs.getLong("ID")));
				articulo.setCodigo(rs.getString("CODIGO"));
				articulo.setDescripcion(rs.getString("DESCRIPCION"));
				articulo.setDescripcionAdicional(rs.getString("DESCRIPCION_ADICIONAL"));
				articulo.setIdUnidadMedida(new Long(rs.getLong("ID_UNIDAD_MEDIDA")));
				articulo.setPeso(new Long(rs.getLong("PESO")));
				articulo.setVolumen(new Long(rs.getLong("VOLUMEN")));
				articulo.setIdSubGrupoArticulo(new Long(rs.getLong("ID_SUB_GRUPO_ARTICULO")));
				articulo.getArticuloSubGrupo().setIdArticuloGrupo(new Long(rs.getLong("ID_ARTICULO_GRUPO")));
				articulo.setIdAreaResponsable(new Long(rs.getLong("ID_AREA_RESPONSABLE")));
				articulo.getArticuloAreaResponsable().setAreaResponsable(rs.getString("AREA_RESPONSABLE"));
				articulo.setValorUnitario(new Long(rs.getLong("VALOR_UNITARIO")));
				articulo.setIdUnidadMedidaCompra(new Long(rs.getLong("ID_UNIDAD_MEDIDA_COMPRA")));
				articulo.setDescripcionCompra(rs.getString("DESCRIPCION_COMPRA"));
				articulo.setIdTipoMaterial(new Long(rs.getLong("ID_TIPO_MATERIAL")));
				articulo.setPropio(rs.getString("PROPIO"));
				articulo.setEstado(rs.getString("ESTADO"));
				articulo.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				articulo.setFechaCrea(rs.getDate("FECHA_CREA"));		
				articulo.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				articulo.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return articulo;
		}
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperationMasterListItemsRetained extends MappingSqlQuery {
		public BaseQueryOperationMasterListItemsRetained(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Articulo articulo = new Articulo();
			articulo.setId(new Long(rs.getLong("ID")));
			articulo.setCodigo(rs.getString("CODIGO"));
			articulo.setDescripcion(rs.getString("DESCRIPCION"));
			return articulo;
		}
    }

    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 "
			  	  	  					+ " ID = ? ";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
    	}
    	public Articulo runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (Articulo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND CODIGO = ? "
			  	  	  					//+ " AND DESCRIPCION = ? "
			  	  	  					//+ " AND DESCRIPCION_ADICIONAL = ? "
			  	  	  					//+ " AND ID_UNIDAD_MEDIDA = ? "
			  	  	  					//+ " AND PESO = ? "
			  	  	  					//+ " AND VOLUMEN = ? "
			  	  	  					//+ " AND ID_SUB_GRUPO_ARTICULO = ? "
			  	  	  					//+ " AND ID_AREA_RESPONSABLE = ? "
			  	  	  					//+ " AND VALOR_UNITARIO = ? "
			  	  	  					//+ " AND ID_UNIDAD_MEDIDA_COMPRA = ? "
			  	  	  					//+ " AND DESCRIPCION_COMPRA = ? "
			  	  	  					//+ " AND ID_TIPO_MATERIAL = ? "
			  	  	  					//+ " AND PROPIO = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public Articulo runQuery(Articulo articulo) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//articulo.getCodigo(),
				//articulo.getDescripcion(),
				//articulo.getDescripcionAdicional(),
				//articulo.getIdUnidadMedida(),
				//articulo.getPeso(),
				//articulo.getVolumen(),
				//articulo.getIdSubGrupoArticulo(),
				//articulo.getIdAreaResponsable(),
				//articulo.getValorUnitario(),
				//articulo.getIdUnidadMedidaCompra(),
				//articulo.getDescripcionCompra(),
				//articulo.getIdTipoMaterial(),
				//articulo.getPropio(),
				//articulo.getEstado(),
				//articulo.getUsuarioCrea(),
				//articulo.getFechaCrea(),
				//articulo.getUsuarioModifica(),
				//articulo.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (Articulo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    public class FindListByCriteriaQuery extends BaseQueryOperationMasterListItemsRetained {
		private static final String sql = " SELECT "
										+ " ID, CODIGO, DESCRIPCION "
										+ " FROM GES_ARTICULO_T "	
										+ " WHERE 1=1 "
										+ " AND PROPIO = ? "
										+ " AND ESTADO LIKE ? ";
    	public FindListByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Articulo articulo) {
			List result =  execute( new Object[]{
				articulo.getPropio(),
				articulo.getEstado()
				});
			if ( result != null && result.size() > 0 ) {
        		return result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = "SELECT "
			+ " A.ID, "
			+ " A.CODIGO, "
			+ " A.DESCRIPCION, "
			+ " A.DESCRIPCION_ADICIONAL, "
			+ " A.ID_UNIDAD_MEDIDA, "
			+ " A.PESO, "
			+ " A.VOLUMEN, "
			+ " A.ID_SUB_GRUPO_ARTICULO, "
			+ " A.ID_AREA_RESPONSABLE, "
			+ " B.AREA_RESPONSABLE, "
			+ " C.ID_ARTICULO_GRUPO, "
			+ " A.VALOR_UNITARIO, "
			+ " A.ID_UNIDAD_MEDIDA_COMPRA, "
			+ " A.DESCRIPCION_COMPRA, "
			+ " A.ID_TIPO_MATERIAL, "
			+ " A.PROPIO, "
			+ " A.ESTADO, "
			+ " A.USUARIO_CREA, "
			+ " A.FECHA_CREA, "
			+ " A.USUARIO_MODIFICA, "
			+ " A.FECHA_MODIFICA "
			+ " FROM "
			+ " GES_ARTICULO_T A "
			+ " INNER JOIN "
			+ " GES_ARTICULO_AREA_RESP_T B "
			+ " ON "
			+ " A.ID_AREA_RESPONSABLE = B.ID "
			+ " INNER JOIN "
			+ " GES_ARTICULO_SUB_GRUPO_T C "
			+ " ON "
			+ " A.ID_SUB_GRUPO_ARTICULO = C.ID "
			+ " WHERE "
			+ " 1=1 "
			+ " AND UPPER(A.CODIGO) LIKE ? "
			+ " AND UPPER(A.DESCRIPCION) LIKE ? "
			+ " AND A.ESTADO = ? ";
		
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Articulo articulo) {
			List result =  execute(new Object[]{
				new String("%" + (articulo.getCodigo() != null && !articulo.getCodigo().equals("") ? articulo.getCodigo().toUpperCase() : "%") + "%"),
				new String("%" + (articulo.getDescripcion() != null && !articulo.getDescripcion().equals("") ? articulo.getDescripcion().toUpperCase() : "%") + "%"),
				articulo.getEstado()
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE
			  	  	  					+ " ESTADO = ? ";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Articulo runQuery(Articulo articulo) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (Articulo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

}
